package netty.http;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

public class Demo02 {

	public static void main(String[] args) {

		NioEventLoopGroup bossGroup = new NioEventLoopGroup(5, new ThreadFactoryBuilder().setNameFormat("boss-%d").setDaemon(true).build());
		NioEventLoopGroup workerGroup = new NioEventLoopGroup(50, new ThreadFactoryBuilder().setNameFormat("boss-%d").setDaemon(true).build());

		ServerBootstrap serverBootstrap = new ServerBootstrap();

		try {
			serverBootstrap.group(bossGroup, workerGroup)
					.channel(NioServerSocketChannel.class)
					.childHandler(new MyHttpInitializer());

			ChannelFuture channelFuture = serverBootstrap.bind(7788).sync();

			channelFuture.addListener(future -> {
				if (future.isSuccess()) {
					System.out.println("服务器启动成功~");
				} else {
					System.out.println("服务器启动失败~");
				}
			});

			channelFuture.channel().closeFuture().sync();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
}

class MyHttpInitializer extends ChannelInitializer<SocketChannel> {

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		// 获得管道
		ChannelPipeline pipeline = ch.pipeline();
		// 向管道加入HTTP处理器
		// HttpServerCodec：是netty提供的http编解码器
		pipeline.addLast("HttpServerCodec", new HttpServerCodec());
		// 添加自定义的HTTP处理器
		pipeline.addLast("MyHttpHandler", new MyHttpHandler());
	}
}

// 可以指定msg的具体类型
class MyHttpHandler extends SimpleChannelInboundHandler<HttpObject> {

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, HttpObject obj) throws Exception {
		if (obj instanceof HttpRequest) {
			// 处理请求
			HttpRequest msg = (HttpRequest) obj;
			// System.out.println(msg.method().name() + " " + msg.uri() + " " + msg.toString());
			// 处理响应
			ByteBuf byteBuf = Unpooled.copiedBuffer("Hello Client ~~~", CharsetUtil.UTF_8);
			FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);
			fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
			// 注意，长度不指定的话客户端就会一直读取，不会结束
			fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());
			ctx.writeAndFlush(fullHttpResponse);
		} else {
			// System.err.println(obj.getClass());
		}
	}
}